<?php


namespace App\Server;

//use Illuminate\Redis;
use Illuminate\Support\Facades\Redis;

class RedisService
{
    private $redis;

    //私有的静态属性（存放本类中唯一实例）
    private static $instance;

    //私有构造方法（防止类外实例化）
    private function __construct()
    {
        $redis = new \Redis();
        $redis->connect('43.143.104.188','6379');
        $redis->auth('wzm232613');
        $redis->select(0);
        $this->redis = $redis;
    }

    //私有克隆方法（防止类外克隆并复制）
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    //对外开放的唯一可以访问的公共方法
    public static function getInstance()
    {
        if (self::$instance)
        {
            return self::$instance;
        } else {
            self::$instance = new self();
            return self::$instance;
        }
    }

    /**
     * Name: 存储有过期时间的key
     * User: 王梓墨
     * Date: 2023/5/30
     * Time:21:18
     * @param $key
     * @param $time
     * @param $val
     * @param $key
     * @param $time
     * @param $val
     * @return bool
     * @return bool
     */
    public function setex($key,$time,$val)
    {
        return $this->redis->setex($key,$time,$val);
    }

    /**
     * Name: 存储key
     * User: 王梓墨
     * Date: 2023/5/30
     * Time:21:21
     * @param $key
     * @param $val
     * @param $key
     * @param $val
     * @return bool
     * @return bool
     */
    public function set($key,$val)
    {
        return $this->redis->set($key,$val);
    }

    /**
     * Name: 获取key
     * User: 王梓墨
     * Date: 2023/5/30
     * Time:21:22
     * @param $key
     * @param $key
     * @return bool|mixed|string
     * @return bool|mixed|string
     */
    public function get($key)
    {
        return $this->redis->get($key);
    }

    /**
     * Name: 保存不同用户的看房信息
     * User: 王梓墨
     * Date: 2023/5/31
     * Time:10:02
     * @param $userId
     * @param $message
     * @param $userId
     * @param $message
     */
    public function setLikeFang($userId,$id,$message)
    {
        Redis::pipeline(function ($pipe) use ($userId,$id, $message) {
            // 将可能喜欢的商品列表保存到 Redis 的有序集合中
            $data = json_encode($message);
            $pipe->zadd("user:{$userId}:fang_like", $id, $data);

            // 控制有序集合中最多只保存 10 条记录，其余记录会被自动移除
//            $pipe->zremrangebyrank("user:{$userId}:might_like", 0, -11);
        });
    }

    /**
     * Name: 取出有序集合中的值
     * User: 王梓墨
     * Date: 2023/6/1
     * Time:10:01
     */
    public function zRange($userId)
    {
        return $this->redis->zRange("laravel_database_user:{$userId}:fang_like",0,-1);
    }

    /**
     * Name: 修改健名对应的sorce值
     * User: 王梓墨
     * Date: 2023/6/1
     * Time:15:47
     * @return int
     * @return int
     */
    public function Zincrby($userId,$id,$name)
    {
        return $this->redis->zIncrBy("laravel_database_user:{$userId}:fang_like",$id,$name);
    }
}
